package com.vito.oa.email.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.search.StringTerm;

public class OaBodyTerm extends StringTerm{

	private static final long serialVersionUID = -714781503161218706L;

	protected OaBodyTerm(String pattern) {
		super(pattern);
	}

	@Override
	public boolean match(Message msg) {
		return matchPart(msg);
	}
	
	 private boolean matchPart(Part p) {
		try {
			/*
			 * Using isMimeType to determine the content type avoids fetching
			 * the actual content data until we need it.
			 */
			if (p.isMimeType("text/*")) {
				String s = (String) p.getContent();
				if (s == null)
					return false;
				return super.match(delHTMLTag(s));
			} else if (p.isMimeType("multipart/*")) {
				Multipart mp = (Multipart) p.getContent();
				int count = mp.getCount();
				for (int i = 0; i < count; i++)
					if (matchPart(mp.getBodyPart(i)))
						return true;
			} else if (p.isMimeType("message/rfc822")) {
				return matchPart((Part) p.getContent());
			}
		} catch (Exception ex) {
		}
		return false;
	}
	
	public static String delHTMLTag(String htmlStr) {
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		return htmlStr.trim(); // 返回文本字符串
	}

}
